package org.jpro.modules.system.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录controller
 */
@Controller
@RequestMapping
public class LoginController {

    /**
     * 首页
     * @return
     */
    @RequestMapping
    public String index() {
        return "system/index";
    }

    /**
     * @return
     */
    @RequestMapping("403")
    @ResponseBody
    public String unauthorizedUrl() {
        return "你没有权限";
    }

    /**
     * 登陆页面
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() || subject.isRemembered()) {
            return "redirect:/";
        }
        return "system/login";
    }

    /**
     * 登录失败
     * @param userName
     * @param model
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
        return "system/login";
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "system/login";
    }

}
